package com.ruoyi.system.service.impl;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.api.domain.*;
import com.ruoyi.system.domain.SchoolConsumeTj;
import com.ruoyi.system.mapper.SchoolClassesMapper;
import com.ruoyi.system.mapper.SchoolPayrecordMapper;
import com.ruoyi.system.utils.AppTCode;
import com.ruoyi.system.utils.WeChatTemplateMsg;
import com.ruoyi.system.mapper.SysDeptMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.utils.WxCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.SchoolConsumeMapper;
import com.ruoyi.system.service.ISchoolConsumeService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

/**
 * 耗课信息Service业务层处理
 * 
 * @author ruoyi
 * @date 2022-11-19
 */
@Service
@Transactional
public class SchoolConsumeServiceImpl implements ISchoolConsumeService 
{
    @Autowired
    private SchoolConsumeMapper schoolConsumeMapper;

    @Autowired
    private SchoolPayrecordMapper schoolPayrecordMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysDeptMapper sysDeptMapper;

    @Autowired
    private SchoolClassesMapper schoolClassesMapper;

    /**
     * 查询耗课信息
     * 
     * @param id 耗课信息ID
     * @return 耗课信息
     */
    @Override
    public SchoolConsume selectSchoolConsumeById(Long id)
    {
        return schoolConsumeMapper.selectSchoolConsumeById(id);
    }

    /**
     * 查询耗课信息列表
     * 
     * @param schoolConsume 耗课信息
     * @return 耗课信息
     */
    @Override
    public List<SchoolConsume> selectSchoolConsumeList(SchoolConsume schoolConsume)
    {
        List<SchoolConsume> list = schoolConsumeMapper.selectSchoolConsumeList(schoolConsume);
        for (SchoolConsume obj:list) {
            SysDept sysDept = sysDeptMapper.selectDeptById(obj.getSchoolId());
            SchoolClasses classes = schoolClassesMapper.selectSchoolClassesById(obj.getClassesId());
            SysUser student = sysUserMapper.selectUserById(obj.getStudentId());
            SysUser teacher = sysUserMapper.selectUserById(obj.getTeacherId());
            obj.setSchoolName(sysDept.getDeptName());
            obj.setClassesName(classes.getClassesName());
            obj.setStudentName(student.getUserName());
            obj.setTeacherName(teacher.getUserName());
        }
        return list;
    }

    @Override
    public List<SchoolConsumeTj> selectSchoolConsumeTjList(SchoolConsume schoolConsume)
    {
        return schoolConsumeMapper.selectSchoolConsumeTjList(schoolConsume);
    }

    @Override
    public List<SchoolConsumeTj> selectSchoolConsumeTjXsList(SchoolConsume schoolConsume)
    {
        return schoolConsumeMapper.selectSchoolConsumeTjXsList(schoolConsume);
    }

    /**
     * 新增耗课信息
     * 
     * @param schoolConsume 耗课信息
     * @return 结果
     */
    @Override
    public int insertSchoolConsume(SchoolConsume schoolConsume)
    {
        Long userId = SecurityUtils.getLoginUser().getSysUser().getUserId();
        List<Long> studentIds = schoolConsume.getStudentIds();
        SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日 HH:mm");
        if (null!=studentIds&&studentIds.size()>0) {
            for (Long studentId:studentIds) {
                SchoolConsume consume = new SchoolConsume();
                consume.setSchoolId(schoolConsume.getSchoolId());
                consume.setClassesId(schoolConsume.getClassesId());
                consume.setStudentId(studentId);
                consume.setConsumeAmount(schoolConsume.getConsumeAmount());
                consume.setTeacherId(userId);
                consume.setCreateTime(DateUtils.getNowDate());
                schoolConsumeMapper.insertSchoolConsume(consume);
                SchoolPayrecord queryPay = new SchoolPayrecord();
                queryPay.setSchoolId(schoolConsume.getSchoolId());
                queryPay.setStudentId(studentId);
                List<SchoolPayrecord> payList = schoolPayrecordMapper.selectSchoolPayrecordList(queryPay);
                if (null!=payList&&payList.size()>0) {
                    BigDecimal remainder = payList.get(0).getRemainder();
                    Long num = payList.get(0).getRemaindnum();
                    remainder = remainder.subtract(schoolConsume.getConsumeAmount());
                    num -= 1;
                    SchoolPayrecord schoolPayrecord = new SchoolPayrecord();
                    schoolPayrecord.setId(payList.get(0).getId());
                    schoolPayrecord.setRemainder(remainder.compareTo(BigDecimal.valueOf(0))<0?BigDecimal.valueOf(0):remainder);
                    schoolPayrecord.setRemaindnum(num<0?0:num);
                    schoolPayrecordMapper.updateSchoolPayrecord(schoolPayrecord);

                    SysDept school = sysDeptMapper.selectDeptById(consume.getSchoolId());
                    SchoolClasses classes = schoolClassesMapper.selectSchoolClassesById(consume.getClassesId());
                    String createDt = format.format(DateUtils.getNowDate());
                    String schoolName = school.getDeptName();
                    String classesName = classes.getClassesName();
                    this.sendMessage(consume.getStudentId(), createDt, schoolName, classesName, schoolConsume.getConsumeAmount(), payList.get(0).getAmount(), remainder, num);
                }
            }
            return studentIds.size();
        }else {
            schoolConsume.setTeacherId(userId);
            schoolConsume.setCreateTime(DateUtils.getNowDate());
            SchoolPayrecord schoolPayrecord = schoolPayrecordMapper.selectSchoolPayrecordById(schoolConsume.getId());
            BigDecimal remainder = schoolPayrecord.getRemainder();
            Long num = schoolPayrecord.getRemaindnum();
            remainder = remainder.subtract(schoolConsume.getConsumeAmount());
            num -= 1;
            schoolPayrecord.setRemainder(remainder.compareTo(BigDecimal.valueOf(0))<0?BigDecimal.valueOf(0):remainder);
            schoolPayrecord.setRemaindnum(num<0?0:num);
            schoolPayrecordMapper.updateSchoolPayrecord(schoolPayrecord);
            SysDept school = sysDeptMapper.selectDeptById(schoolConsume.getSchoolId());
            SchoolClasses classes = schoolClassesMapper.selectSchoolClassesById(schoolConsume.getClassesId());
            String createDt = format.format(DateUtils.getNowDate());
            String schoolName = school.getDeptName();
            String classesName = classes.getClassesName();
            this.sendMessage(schoolConsume.getStudentId(), createDt, schoolName, classesName, schoolConsume.getConsumeAmount(), schoolPayrecord.getAmount(), remainder, num);
            return schoolConsumeMapper.insertSchoolConsume(schoolConsume);
        }
    }

    private void sendMessage(Long studentId, String createDt, String schoolName, String classesName, BigDecimal consume, BigDecimal amount, BigDecimal remainder, Long num) {
        SysUser student = sysUserMapper.selectUserById(studentId);
        String access_token = WxCode.getInstance().getAccessToken(student.getAppId());
        String openId = student.getHopenId();// openId代表一个唯一微信用户，即微信消息的接收人
        String templateId = AppTCode.getValueByKey(student.getAppId());;// 公众号的模板id(也有相应的接口可以查询到)
        String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + access_token;
        Map<String, WeChatTemplateMsg> sendMag = new HashMap<String, WeChatTemplateMsg>();
        if ("wxae0f0d0aef1a8645".equals(student.getAppId())) {
            sendMag.put("first", new WeChatTemplateMsg("关于耗课提醒通知"));
            sendMag.put("keyword1", new WeChatTemplateMsg(schoolName));
            sendMag.put("keyword2", new WeChatTemplateMsg(classesName));
            sendMag.put("keyword3", new WeChatTemplateMsg(consume.toString()+"元（价值）"));
            sendMag.put("keyword4", new WeChatTemplateMsg(createDt));
            sendMag.put("keyword5", new WeChatTemplateMsg(student.getUserName()));
            sendMag.put("remark", new WeChatTemplateMsg("总缴费："+amount.toString()+"元（价值），\r\n余额："+remainder.toString()+"元（价值），\r\n剩余次数："+num));
        }else if ("wxff9cb9b0b37dfef8".equals(student.getAppId())) {
            sendMag.put("thing8", new WeChatTemplateMsg(schoolName));
            sendMag.put("thing2", new WeChatTemplateMsg(classesName));
            sendMag.put("amount5", new WeChatTemplateMsg(consume.toString()+"元（价值）"));
            sendMag.put("time9", new WeChatTemplateMsg(createDt));
            sendMag.put("thing7", new WeChatTemplateMsg(student.getUserName()));
        }

        //拼接base参数
        Map<String, Object> sendBody = new HashMap<>();
        sendBody.put("touser", openId);               // openId
        sendBody.put("template_id", templateId);      // 模板Id
        sendBody.put("data", sendMag);                // 模板参数
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> forEntity = restTemplate.postForEntity(url, sendBody, String.class);
    }

    /**
     * 修改耗课信息
     * 
     * @param schoolConsume 耗课信息
     * @return 结果
     */
    @Override
    public int updateSchoolConsume(SchoolConsume schoolConsume)
    {
        Long userId = SecurityUtils.getLoginUser().getSysUser().getUserId();
        schoolConsume.setTeacherId(userId);
        return schoolConsumeMapper.updateSchoolConsume(schoolConsume);
    }

    /**
     * 批量删除耗课信息
     * 
     * @param ids 需要删除的耗课信息ID
     * @return 结果
     */
    @Override
    public int deleteSchoolConsumeByIds(Long[] ids)
    {
        return schoolConsumeMapper.deleteSchoolConsumeByIds(ids);
    }

    /**
     * 删除耗课信息信息
     * 
     * @param id 耗课信息ID
     * @return 结果
     */
    @Override
    public int deleteSchoolConsumeById(Long id)
    {
        return schoolConsumeMapper.deleteSchoolConsumeById(id);
    }
}
